<template>
  <view class="edit-equipment-container">
    <uni-section title="设备信息" type="line"></uni-section>

    <view class="form-container">
      <uni-forms ref="form" :model="formData" :rules="rules" label-width="180rpx">
        <!-- 设备类型 -->
        <uni-forms-item label="设备类型" name="equipmentTypeId" required>
          <uni-data-select v-model="formData.equipmentTypeId" :localdata="typeOptions" placeholder="请选择设备类型" />
        </uni-forms-item>
        <!-- 设备名称 -->
        <uni-forms-item label="设备名称" name="equipmentName" required>
          <uni-easyinput v-model="formData.equipmentName" placeholder="请输入设备名称" :clearable="true" />
        </uni-forms-item>

        <!-- 设备编号 -->
        <uni-forms-item label="设备编号" name="equipmentCode" required>
          <uni-easyinput v-model="formData.equipmentCode" placeholder="请输入设备编号" :clearable="true" />
        </uni-forms-item>

        <!-- 设备型号 -->
        <uni-forms-item label="设备型号" name="model" required>
          <uni-easyinput v-model="formData.model" placeholder="请输入设备型号" :clearable="true" />
        </uni-forms-item>

        <!-- 出厂编号 -->
        <uni-forms-item label="出厂编号" name="serialNumber">
          <uni-easyinput v-model="formData.serialNumber" placeholder="请输入出厂编号" :clearable="true" />
        </uni-forms-item>
        <!-- 数量 -->
        <uni-forms-item label="数量" name="quantity" required>
          <uni-easyinput v-model="formData.quantity" placeholder="请输入数量" :clearable="true" />
        </uni-forms-item>
        <!-- 单位 -->
        <uni-forms-item label="单位" name="unit" required>
          <uni-easyinput v-model="formData.unit" placeholder="请输入单位" :clearable="true" />
        </uni-forms-item>

        <!-- 设备所在地 -->
        <uni-forms-item label="设备所在地" name="location" required>
          <uni-easyinput v-model="formData.location" placeholder="请输入设备所在地" :clearable="true" />
        </uni-forms-item>

        <!-- 设备状态 -->
        <uni-forms-item label="设备状态" name="status" required>
          <uni-data-select v-model="formData.status" :localdata="statusOptions" placeholder="请选择设备状态" />
        </uni-forms-item>

        <!-- 设备描述 -->
        <uni-forms-item label="备注" name="remark">
          <uni-easyinput v-model="formData.remark" type="textarea" placeholder="请输入设备描述" :autoHeight="true"
            :maxlength="200" />
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn cancel" @click="handleCancel">取消</button>
      <button class="action-btn submit" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script>
import { listEquipmentTypes, getEquipment, updateEquipment } from '@/api/equipment/main'
import { getDicts } from '@/api/system/dict/data'

export default {
  data() {
    return {
      equipmentId: null,
      formData: {
        equipmentName: '',
        equipmentCode: '',
        equipmentTypeId: '',
        status: '',
        model: '',
        location: '',
        serialNumber: '',
        purchaseDate: '',
        remark: '',
        quantity: '',
        unit: '',
      },
      rules: {
        equipmentName: {
          rules: [
            { required: true, errorMessage: '请输入设备名称' },
            { minLength: 1, maxLength: 50, errorMessage: '设备名称长度为1-50个字符' }
          ]
        },
        equipmentCode: {
          rules: [
            { required: true, errorMessage: '请输入设备编号' },
            { minLength: 1, maxLength: 30, errorMessage: '设备编号长度为1-30个字符' }
          ]
        },
        equipmentTypeId: {
          rules: [
            { required: true, errorMessage: '请选择设备类型' }
          ]
        },
        status: {
          rules: [
            { required: true, errorMessage: '请选择设备状态' }
          ]
        },
        model: {
          rules: [
            { required: true, errorMessage: '请输入设备型号' }
          ]
        },
        location: {
          rules: [
            { required: true, errorMessage: '请输入设备所在地' }
          ]
        },
        quantity: {
          rules: [
            { required: true, errorMessage: '请输入数量' }
          ]
        },
        unit: {
          rules: [
            { required: true, errorMessage: '请输入单位' }
          ]
        }
      },
      typeOptions: [],
      statusOptions: []
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.equipmentId = options.id
      await this.fetchTypeOptions()
      await this.fetchStatusOptions()
      await this.fetchEquipmentDetail()
    } else {
      uni.showToast({
        title: '缺少设备ID',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  methods: {
    // 获取设备详情
    async fetchEquipmentDetail() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const res = await getEquipment(this.equipmentId)
        const data = res && res.data ? res.data : res

        // 回填表单数据
        this.formData = {
          equipmentName: data.equipmentName || data.name || '',
          equipmentCode: data.equipmentCode || data.code || '',
          equipmentTypeId: data.equipmentTypeId || data.typeId || '',
          status: data.status || '',
          model: data.model || '',
          location: data.location || '',
          serialNumber: data.serialNumber || '',
          purchaseDate: data.purchaseDate || '',
          remark: data.remark || data.description || '',
          quantity: data.quantity || '',
          unit: data.unit || ''
        }

        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取设备详情失败:', error)
        uni.showToast({
          title: '获取设备详情失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    // 获取设备类型选项
    async fetchTypeOptions() {
      try {
        const res = await listEquipmentTypes()
        const list = (res && res.rows) ? res.rows : res
        this.typeOptions = (Array.isArray(list) ? list : []).map(item => ({
          text: item.typeName,
          value: item.id
        }))
      } catch (e) {
        console.error('获取设备类型失败:', e)
        uni.showToast({
          title: '获取设备类型失败',
          icon: 'none'
        })
      }
    },

    // 获取设备状态选项
    async fetchStatusOptions() {
      try {
        const res = await getDicts('equipment_status')
        const list = (res && res.data) ? res.data : res
        this.statusOptions = (Array.isArray(list) ? list : []).map(item => ({
          text: item.dictLabel,
          value: item.dictValue
        }))
      } catch (e) {
        console.error('获取设备状态失败:', e)
        // 使用默认状态选项
        this.statusOptions = [
          { text: '在线', value: '1' },
          { text: '离线', value: '2' },
          { text: '告警', value: '3' },
          { text: '维修中', value: '5' },
          { text: '已报废', value: '6' }
        ]
      }
    },

    // 取消操作
    handleCancel() {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消修改设备吗？未保存的数据将丢失。',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate().then(async (valid) => {
        if (valid) {
          try {
            uni.showLoading({
              title: '保存中...'
            })

            // 调用修改设备的API
            const updateData = {
              ...this.formData,
              id: this.equipmentId
            }
            const res = await updateEquipment(updateData)

            uni.hideLoading()
            uni.showToast({
              title: '设备修改成功',
              icon: 'success'
            })

            // 延迟返回上一页
            setTimeout(() => {
              // 标记上一页需要刷新
              try { uni.setStorageSync('refresh_equipment_list', Date.now()) } catch (e) { }
              uni.navigateBack()
            }, 1500)

          } catch (error) {
            uni.hideLoading()
            console.error('修改设备失败:', error)
            uni.showToast({
              title: '修改设备失败',
              icon: 'none'
            })
          }
        }
      }).catch((errors) => {
        console.log('表单验证失败:', errors)
        uni.showToast({
          title: '请检查输入信息',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-equipment-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-btn.cancel {
  background: #f0f0f0;
  color: #666;
}

.action-btn.submit {
  background: #007AFF;
  color: #fff;
}

.action-btn:active {
  opacity: 0.8;
}

// 表单项样式调整
/* 缩小每个表单项上下间距，覆盖组件内默认的 22px */
.form-container :deep(.uni-forms-item) {
  margin-bottom: 8px !important;
  /* 覆盖 H5 默认 22px */
  padding-bottom: 8px !important;
  /* 覆盖 nvue 默认 22px */
}

/* 覆盖边框模式下的默认上下 padding（10px 0），防止撑开间距 */
.form-container :deep(.uni-forms-item--border) {
  padding: 4px 0 !important;
  /* 覆盖边框模式默认 10px 0 */
}

/* 缩小错误信息与控件的间距 */
.form-container :deep(.uni-forms-item__error) {
  padding-top: 2px !important;
}

:deep(.uni-forms-item__label) {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

:deep(.uni-easyinput__content) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-easyinput__content.is-focus) {
  border-color: #007AFF;
  background: #fff;
}

:deep(.uni-data-select) {
  border-radius: 12rpx;
  border: 1rpx solid #eee;
  background: #f9f9f9;
}

:deep(.uni-data-select.is-focus) {
  border-color: #007AFF;
  background: #fff;
}
</style>
